<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :rules="queryForm" :inline="true" v-show="showSearch"
             label-width="68px">
      <el-form-item label="访客姓名" prop="visitName">
        <el-input
          v-model="queryParams.visitName"
          placeholder="请输入访客姓名"
          clearable
          size="small"
          maxlength="30"
          show-word-limit
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="访客电话" prop="visitPhone">
        <el-input
          v-model="queryParams.visitPhone"
          placeholder="请输入访客电话"
          clearable
          size="small"
          maxlength="20"
          show-word-limit
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="approverState">
        <el-select v-model="queryParams.approverState" placeholder="审批状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="info" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['server:visitor:add']"
          >新增
          </el-button>
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="handleDelete"
            v-hasPermi="['server:visitor:remove']"
          >删除
          </el-button>
          <el-button
            type="info"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['server:visitor:export']"
          >导出
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
      </el-row>
    </el-form>

    <el-table v-loading="loading" :data="visitorRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" width="80" align="center" key="visitId" prop="visitId"
                       v-if="columns[0].visible"/>
      <el-table-column label="访客姓名" align="center" key="visitName" prop="visitName" v-if="columns[1].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="访客电话" align="center" key="visitPhone" prop="visitPhone" width="120"
                       v-if="columns[2].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="访客身份证" align="center" key="visitCard" prop="visitCard" width="180"
                       v-if="columns[3].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="访客性别" align="center" key="visitSex" prop="visitSex" :formatter="sexFormat"
                       v-if="columns[4].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="访客年龄" align="center" key="visitAge" prop="visitAge" v-if="columns[5].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="访客体温" align="center" key="visitTemperature" prop="visitTemperature"
                       v-if="columns[6].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="访问公司" align="center" key="visitComp" prop="visitComp" width="180"
                       v-if="columns[7].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="访问事由" align="center" key="visitMatter" prop="visitMatter"
                       v-if="columns[8].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="接待人姓名" align="center" key="user.userName" prop="user.userName" v-if="columns[9].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="审批状态" align="center" key="approverState" prop="approverState" :formatter="statusFormat"
                       v-if="columns[10].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="创建时间" align="center" key="createTime" prop="createTime" width="180"
                       v-if="columns[11].visible"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.approverState === '0'"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['server:visitor:edit']"
          >修改
          </el-button>
          <el-button
            v-if="scope.row.approverState === '0'"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleUpdateState(scope.row)"
            v-hasPermi="['server:visitor:changeState']"
          >审批
          </el-button>
          <el-button
            v-else
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleSelect(scope.row)"
            v-hasPermi="['server:visitor:query']"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['server:visitor:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改访客记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="1.5">
            <el-form-item label="访客姓名" prop="visitName">
              <el-input v-model="form.visitName" placeholder="请输入访客姓名" maxlength="30"/>
            </el-form-item>
            <el-form-item label="访客电话" prop="visitPhone" maxlength="20">
              <el-input v-model="form.visitPhone" placeholder="请输入访客电话"/>
            </el-form-item>
            <el-form-item label="访客身份证" prop="visitCard" maxlength="18">
              <el-input v-model="form.visitCard" placeholder="请输入访客身份证"/>
            </el-form-item>
            <el-form-item label="访客体温" prop="visitTemperature" maxlength="5">
              <el-input v-model="form.visitTemperature" placeholder="请输入访客体温"/>
            </el-form-item>
            <el-form-item label="访问公司" prop="visitComp">
              <el-select v-model="form.visitComp"
                         filterable
                         placeholder="请输入企业名称"
                         remote
                         clearable
                         reserve-keyword
                         style="width:100%"
                         @change="changeCompId"
                         :remote-method="Tolikesearch">
                <el-option
                  v-for="item in compOptions"
                  :key="item.compId"
                  :label="item.compName"
                  :value="item.compId">
                </el-option>
              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="1.5">
            <el-form-item label="访问事由" prop="visitMatter">
              <el-input v-model="form.visitMatter" placeholder="请输入访问事由" maxlength="100"/>
            </el-form-item>
            <el-form-item label="接待人姓名" prop="userId">
              <el-select v-model="form.userId" placeholder="请选择"
                         style="width:100%"
                         reserve-keyword>
                <el-option
                  v-for="item in userOptions"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="访问时间" prop="date">
              <el-date-picker
                v-model="form.date"
                size="small"
                value-format="yyyy-MM-dd"
                type="date"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item style="margin-top: 0" prop="startTime">
              <el-time-select
                style="width: 360px;"
                placeholder="开始时间"
                v-model="form.startTime"
                :picker-options="{
                                start: '09:00',
                                step: '00:30',
                                end: '18:30',
                                maxTime:form.endTime
                                }">
              </el-time-select>
            </el-form-item>
            <el-form-item prop="endTime">
              <el-time-select
                style="width: 100%;"
                placeholder="结束时间"
                v-model="form.endTime"
                :picker-options="{
                                start: '09:00',
                                step: '00:30',
                                end: '18:30',
                                minTime: form.startTime
                                 }">
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" style="width: 100%" type="textarea" placeholder="请输入内容" maxlength="200"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--审批-->
    <el-dialog :title="title" :visible.sync="change" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="访客姓名" prop="visitName">
              {{ form.visitName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访客电话" prop="visitPhone">
              {{ form.visitPhone }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访客身份证" prop="visitCard">
              {{ form.visitCard }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访客性别" prop="visitSex">
              <div v-if="form.visitSex ==='0'">男</div>
              <div v-else-if="form.visitSex ==='1'">女</div>
              <div v-else-if="form.visitSex ==='3'">未知</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访客年龄" prop="visitAge">
              {{ form.visitAge }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访客体温" prop="visitTemperature">
              {{ form.visitTemperature }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访问公司" prop="visitComp">
              {{ form.visitComp }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访问时间">
              {{ form.visitTime }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="离开时间">
              {{ form.leftTime }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态类型" prop="approverState">
              <el-radio-group v-model="form.approverState">
                <el-radio label="2">拒绝</el-radio>
                <el-radio label="1">通过</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--查看-->
    <el-dialog :title="title" :visible.sync="look" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="访客姓名：" prop="visitName">
              {{ form.visitName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访客电话：" prop="visitPhone">
              {{ form.visitPhone }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访客身份证：" prop="visitCard">
              {{ form.visitCard }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访客性别：" prop="visitSex">
              <div v-if="form.visitSex ==='0'">男</div>
              <div v-else-if="form.visitSex ==='1'">女</div>
              <div v-else-if="form.visitSex ==='3'">未知</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访客年龄：" prop="visitAge">
              {{ form.visitAge }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访客体温：" prop="visitTemperature">
              {{ form.visitTemperature }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访问公司：" prop="visitComp">
              {{ form.visitComp }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访问事由：" prop="visitMatter">
              {{ form.visitMatter }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访问时间：" prop="visitMatter">
              {{ form.visitTime }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="离开时间：" prop="visitMatter">
              {{ form.leftTime }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批人姓名：" prop="approverName">{{ form.approverName }}
              <!--              <el-select v-model="form.approverId" disabled placeholder="请选择">-->
              <!--                <el-option-->
              <!--                  v-for="item in userOptions"-->
              <!--                  :key="item.id"-->
              <!--                  :label="item.label"-->
              <!--                  :value="item.id"-->
              <!--                ></el-option>-->
              <!--              </el-select>-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批时间：" prop="approverTime">
              {{ form.approverTime }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态类型：" prop="approverState">
              {{ selectDictLabel(statusOptions, form.approverState) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注：" prop="remark">
              {{ form.remark }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

  </div>
</template>
<script>
import {
  addVisitorRecord,
  getVisitorRecord,
  deleteVisitorRecord,
  listVisitorRecord,
  updateVisitorRecord,
  changeVisitorRecordApproverState,
  exprotVisitorRecord,
} from '@/api/server/visitor/visitor'
import {userSelect} from "@/api/system/user";
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {listCompany} from "../../../api/server/companies/company";
import {parseTime} from "../../../utils/project";
import {listUser} from "../../../api/system/user";

export default {
  name: 'visitor',
  comments: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 访客记录信息表格数据
      visitorRecordList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      //是否显示审批状态弹出层
      change: false,
      //是否显示查看弹出层
      look: false,
      //接待人下拉框选项
      userOptions: undefined,
      //接待人姓名
      userName: undefined,
      // 状态数据字典
      statusOptions: [],
      //性别状态字典
      sexOptions: [],
      //企业列表
      compOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        visitName: undefined,
        visitPhone: undefined,
        userId: undefined,
        approverState: undefined
      },
      // 表单参数
      form: {
        approverName: "",
        userName: ""
      },
      //列信息
      columns: [
        {key: 0, label: "序号", visible: true},
        {key: 1, label: "访客姓名", visible: true},
        {key: 2, label: "访客电话", visible: true},
        {key: 3, label: "访客身份证", visible: true},
        {key: 4, label: "访客性别", visible: true},
        {key: 5, label: "访客年龄", visible: true},
        {key: 6, label: "访客体温", visible: true},
        {key: 7, label: "访问公司", visible: true},
        {key: 8, label: "访问事由", visible: true},
        {key: 9, label: "接待人姓名", visible: true},
        {key: 10, label: "审批状态", visible: true},
        {key: 11, label: "创建时间", visible: true},
      ],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      queryForm: {
        visitName: [{pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/, message: '不能为特殊字符', trigger: 'blur'}],
        visitPhone: [{pattern: /^[0-9]*$/, message: '请输入数字', trigger: 'blur'}],
      },
      // 表单校验
      rules: {
        visitName: [
          {required: true, message: '访客姓名不能为空', trigger: 'blur'}
        ],
        visitCard: [
          {
            required: true,
            pattern: /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/,
            message: '请输入正确的身份证',
            trigger: 'blur'
          }
        ],
        visitPhone: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机',
            trigger: 'blur'
          }
        ],
        date: [
          {required: true, message: '访问时间不能为空', trigger: 'change'}
        ],
        startTime: [
          {required: true, message: '访问时间不能为空', trigger: 'change'}
        ],
        endTime: [
          {required: true, message: '访问时间不能为空', trigger: 'change'}
        ],
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('t_visitor_approverState').then(response => {
      this.statusOptions = response.data
    })
    this.getDicts('sys_user_sex').then(response => {
      this.sexOptions = response.data
    })
  },
  methods: {
    /** 查询访客记录列表 */
    getList() {
      this.loading = true
      let date = this.queryParams.date
      let startTime = this.queryParams.startTime
      let endTime = this.queryParams.endTime
      this.queryParams.visitTime = parseTime(this.queryParams.date + " " + this.queryParams.startTime)
      this.queryParams.leftTime = parseTime(this.queryParams.date + " " + this.queryParams.endTime)
      listVisitorRecord(this.queryParams).then(response => {
        let arr = response.rows
        this.visitorRecordList = response.rows
        for (let i in arr) {
          this.visitorRecordList[i].visitCard = arr[i].visitCard.replace(/^(\d{6})\d+(\d{4})$/, '$1********$2')
          this.visitorRecordList[i].visitPhone = arr[i].visitPhone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
        }
        this.total = response.total
        this.loading = false
      })
    },
    //搜索发起请求 传入值为当前select输入的值
    Tolikesearch(query) {
      listCompany({compName: query}).then(res => {
        this.compOptions = res.rows
      })
    },
    changeCompId(e){
      this.form.compId = e
      this.getUserList(this.form.compId)
      console.log("!!!!"+e)
      for(let i in this.compOptions){
        if (this.compOptions[i] === this.form.compId){
          this.form.compName = this.compOptions[i].compName
        }
      }
    },
    /** 查询员工下拉树结构 */
    getUserList(data) {
      listUser({compId:data}).then(response => {
        console.log("~~~~~~~"+response)
        this.userOptions = response.rows
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.userId = data.id
      this.getList()
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.approverState)
    },
    // 性别字典翻译
    sexFormat(row, column) {
      return this.selectDictLabel(this.sexOptions, row.visitSex)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.change = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        visitName: undefined,
        visitPhone: undefined,
        approverState: undefined,
        date: undefined,
        startTime: undefined,
        endTime: undefined,
        remark: undefined,
        user: undefined,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.$refs['queryForm'].validate(valid => {
        if (valid) {
          this.getList()
        }
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.visitId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 查看按钮操作 */
    handleSelect(row) {
      this.reset()
      this.getUserList()
      const visitId = row.visitId || this.visitId
      getVisitorRecord(visitId).then(response => {
        this.form = response.data
        this.form.approverName = this.form.user.approverName
        this.look = true
        this.title = '查看审批信息'
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getUserList()
      this.open = true
      this.title = '添加访客记录'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getUserList()
      const visitId = row.visitId || this.visitId
      getVisitorRecord(visitId).then(response => {
        this.form = response.data
        this.form.userId = response.userId
        this.form.date = ""
        this.form.startTime = ""
        this.form.endTime = ""
        this.form.date = response.data.visitTime.substring(0, 10)
        this.form.startTime = response.data.visitTime.substring(11, 16)
        this.form.endTime = response.data.leftTime.substring(11, 16)
        this.open = true
        this.title = '修改访客记录'
      })
    },
    /** 审批按钮操作 */
    handleUpdateState(row) {
      this.reset()
      this.getUserList()
      const visitId = row.visitId || this.visitId
      getVisitorRecord(visitId).then(response => {
        this.form = response.data
        this.change = true
        this.title = '审批访客记录'
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.approverState !== '0' && this.form.visitId !== undefined) {
            this.form.approverTime = parseTime(new Date())
            changeVisitorRecordApproverState(this.form).then(response => {
              this.msgSuccess('审批成功')
              this.change = false
              this.getList()
            })
          } else if (this.form.visitId !== undefined) {
            this.form.visitTime = parseTime(this.form.date + " " + this.form.startTime)
            this.form.leftTime = parseTime(this.form.date + " " + this.form.endTime)
            updateVisitorRecord(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            this.form.visitTime = parseTime(this.form.date + " " + this.form.startTime)
            this.form.leftTime = parseTime(this.form.date + " " + this.form.endTime)
            addVisitorRecord(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const visitId = row.visitId || this.ids
      if (visitId.length === 0) {
        this.$confirm('请选择需要删除的记录')
      } else {
        this.$confirm('是否确认删除该数据项?', '警告', {
          cancelButtonClass: 'btn-custom-cancel',
          closeOnClickModal: false,
          type: 'warning'
        }).then(function () {
          return deleteVisitorRecord(visitId)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
      }
    },


    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有访客记录数据项？', '提示', {
        cancelButtonClass: 'btn-custom-cancel',
        closeOnClickModal: false,
        type: 'info'
      }).then(function () {
        return exprotVisitorRecord(queryParams)
      }).then(response => {
        this.download(response.msg)
      })
    }
  }
}
</script>
